var constant = require('../const');
var models = require('../models');
var AV = require('leanengine')

//每隔3小时去检测时间到的恋人，分手
function brokeSweet(req, res) {
	var MLSweetheart = models.MLSweetheart;
	var sweetQuery = new AV.Query(MLSweetheart);
	sweetQuery.equalTo("status", 1);
	sweetQuery.find({
		success: function(results) {
			for (var i = 0; i < results.length; i++) {
				var sweet = results[i];

				var together_time = sweet.get("togetherDate");
				var billTime = together_time.getTime() / 1000;

				var nowTime = (new Date()).getTime() / 1000;
				// 预期结束需要的时间2天
				var finishedSeconds = 48 * 60 * 60;
				// 如果服务结束超过48小时则关闭订单
				if (nowTime - billTime > finishedSeconds) {
					sweet.set("status", 0);
					sweet.save(null, {
						success: function(sweet) {
							AV.Cloud.run('sendSysMsg', {
								"touserId": [sweet.get("winner").id,sweet.get("sponsor").id],
								"type": 0,
								"msg": "48小时试恋时间到了。如果你们决定继续试恋，请再次申请。"
							}, {
								success: function(result) {
								},
								error: function(error) {
								}
							});
							AV.Cloud.run('sendSweetApplyCMDMsg', {
								"fromuserId":sweet.get("winner").id,
								"touserId": sweet.get("sponsor").id,
								"actions": com.pocketsweet.SWEET_DELETE,
							}, {
								success: function(result) {
								},
								error: function(error) {
								}
							});
							AV.Cloud.run('sendSweetApplyCMDMsg', {
								"fromuserId":sweet.get("sponsor").id,
								"touserId": sweet.get("winner").id,
								"actions": com.pocketsweet.SWEET_DELETE,
							}, {
								success: function(result) {
								},
								error: function(error) {
								}
							});

						},
						error: function(sweet, error) {
							res.error(error);
						}
					});
				}
			};
			res.success("未评价订单处理结束");
		},
		error: function(error) {
			res.error();
		}
	});
}

exports.brokeSweet = brokeSweet;